<template>
  <div class="main">
    <el-card class="box-card">
      <el-divider content-position="left">第一步 题目上传</el-divider>
      <el-form ref="problemForm" :model="formData">
        <el-form-item label="题目">
          <el-input v-model="formData.title"></el-input>
        </el-form-item>
        <el-form-item label="标签">
          <el-button @click="openDialog">选择标签</el-button>
          <el-divider content-position="left">已选择的标签</el-divider>
          <div v-if="selectedTags.length">
            <el-tag
                v-for="tag in selectedTags"
                :key="tag"
                closable
                @close="toggleTag(tag)"
                class="selected-tag">
              {{ tag }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item label="难度">
          <el-rate v-model="formData.difficulty" :max="5"></el-rate>
        </el-form-item>
        <el-form-item label="题目描述">
          <el-input
              type="textarea"
              v-model="formData.description"
              :rows="36">
          </el-input>
        </el-form-item>
        <el-button size="large" type="primary" @click="submitForm">下一步</el-button>
      </el-form>
    </el-card>

    <el-dialog
        title="选择标签"
        v-model="showTagDialog"
        class="dialog-main"
        width="500px">
      <div v-if="loading">加载中...</div>
      <div v-else v-for="(tagType, index) in uniqueTagTypes" :key="index">
        <h3>{{ tagType }}</h3>
        <div class="tag-container">
          <el-checkbox-group v-model="selectedTags" class="custom-checkbox-group">
            <el-checkbox
                v-for="tag in tags.filter(t => t.tagType === tagType)"
                :label="tag.tag"
                :key="tag.id"
                class="custom-checkbox">
              {{ tag.tag }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {ref, onMounted, computed} from 'vue';
import axios from 'axios';
import {ElMessage} from 'element-plus';
import {API_BASE_URL, AUTH_TOKEN} from '@/config.ts';
import router from "@/router";
import {useRoute} from 'vue-router';
import { useStore } from 'vuex';

const route = useRoute();
const formData = ref({
  id:"",
  title: "",
  difficulty: 0,
  description: "",
  tags: [],
  isCreated: false,
  codeId: "",
  isBan:"",
  commitNum:"",
  passNum:""
});

const tags = ref([]);  // 所有标签数据
const selectedTags = ref([]); // 已选标签名字符串数组
const showTagDialog = ref(false); // 控制标签选择弹框的显示
const uniqueTagTypes = computed(() => [...new Set(tags.value.map(tag => tag.tagType))]); // 根据标签类型分组
const loading = ref(false); // 控制加载状态
const store = useStore();
let problemData = null;

// 解析标签字符串为字符串数组
const parseTags = (tagsString: string) => {
  try {
    return JSON.parse(tagsString);  // 返回标签名数组
  } catch (error) {
    console.error('标签解析失败', error);
    return [];
  }
};

// 检查是否有传递的题目数据，并将其填充到表单中
onMounted(() => {
  if (route.query) {
    try {
      problemData = {
        editing:route.query.editing as string,
        id: route.query.id as string,
        title: route.query.title as string,
        description: route.query.description as string,
        difficulty: parseInt(route.query.difficulty as string, 10),
        tags: parseTags(route.query.tags as string), // 解析标签名
        codeId : route.query.codeId as string,
        isBan: route.query.isBan as string,
        commitNum: route.query.commitNum as string,
        passNum: route.query.passNum as string
      };
      formData.value.id=problemData.id;
      formData.value.title = problemData.title;
      formData.value.description = problemData.description;
      formData.value.difficulty = problemData.difficulty;
      selectedTags.value = problemData.tags;
      formData.value.isCreated = true;
      formData.value.codeId=problemData.codeId;
      formData.value.isBan=problemData.isBan;
      formData.value.commitNum=problemData.commitNum;
      formData.value.passNum=problemData.passNum;
      console.log("fromData")
      console.log(formData.value)

    } catch (error) {
      ElMessage.error('传递的题目数据解析失败');
    }
  }
});

// 提交表单处理
const submitForm = async () => {
  // 将选中的标签名直接赋值给 formData 的 tags
  formData.value.tags = selectedTags.value;
  try {
    console.log(formData.value)
    const response = await axios.post(`${API_BASE_URL}/ProblemsGroup/problems/uploadProblems`, formData.value, {
      headers: {
        'Content-Type': 'application/json',
        'token': AUTH_TOKEN
      }
    });
    if (response.data.code === 200) {
      ElMessage.success("题目上传完成");

      // 根据 problemData.id 进行跳转
      if (problemData && problemData.editing==='1') {
        await store.dispatch('updateProblemId', response.data.data.id);
        await router.push({
          path: '/UploadTestGroup',
          query: {
            id: problemData.id,
            editing: problemData.editing
          }
        });
      } else {
        await router.push({
          path: '/UploadTestGroup',
          query: {
            id: response.data.data.id
          }
        });
      }

    } else {
      ElMessage.error(`上传失败: ${response.data.msg}`);
    }
  } catch (error) {
    ElMessage.error('提交表单时出错');
  }
};

// 打开选择标签的对话框
const openDialog = () => {
  showTagDialog.value = true;
};

// 删除标签
const toggleTag = (tagToRemove: string) => {
  selectedTags.value = selectedTags.value.filter(tag => tag !== tagToRemove);
};

// 从后台获取标签
const fetchTags = async () => {
  loading.value = true;
  try {
    const response = await axios.get(`${API_BASE_URL}/ProblemsGroup/tag`, {
      headers: {'Content-Type': 'application/json', 'token': AUTH_TOKEN},
      params: {query: 'all'}
    });
    if (response.data.code === 200) {
      tags.value = response.data.data;
    } else {
      ElMessage.error('加载标签失败');
    }
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchTags();
});

</script>


<style scoped>
.box-card {
  margin-bottom: 20px;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
}

.selected-tag {
  margin-right: 5px;
  margin-top: 5px;
}

.custom-checkbox-group .el-checkbox {
  margin-right: 10px;
}

.custom-dialog .dig-button {
  display: flex;
  justify-content: space-between;
}
</style>
